package com.lin.lazybone.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.lin.lazybone.R;
import com.lin.lazybone.adapter.OrderListAdapter;
import com.lin.lazybone.application.BaseActivity;
import com.lin.lazybone.entity.Order;
import com.lin.lazybone.entity._User;
import com.lin.lazybone.utils.L;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;


/**
 * Created by mr.lin on 2017/10/31.
 */

public class OrderListActivity extends BaseActivity implements OrderListAdapter.Callback
{
    private CollapsingToolbarLayout collapsingToolbar;
    private List<Order> orderList = new ArrayList<>();;
    private NestedListView order_ListView;
    private OrderListAdapter adapter;
    private FloatingActionButton works;



    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //使状态栏透明化
        if (Build.VERSION.SDK_INT >= 21)
        {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_orderlist);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        initData();
        initView();

    }

    private void initData()
    {
//        for (int i = 0; i < 10; i++)
//        {
//            Order order = new Order();
//            order.setOrder_del_type("申通" + i);
//            order.setOrder_type(true);
//            order.setOrder_price("80");
//            orderList.add(order);
//        }

        //获取服务器上订单数据
        getOrderData();
    }

    private void initView()
    {
        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("需求列表");
        works = (FloatingActionButton) findViewById(R.id.mywork_fab);
        works.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(OrderListActivity.this, MyWorksActivity.class));
            }
        });
        order_ListView = (NestedListView) findViewById(R.id.activity_orderlist);
        adapter = new OrderListAdapter(this, orderList, this, 1);
        order_ListView.setAdapter(adapter);
        //添加动画
        LayoutAnimationController lac = new LayoutAnimationController(AnimationUtils.loadAnimation(this, R.anim.zoom_in));
        lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
        order_ListView.setLayoutAnimation(lac);
        order_ListView.startLayoutAnimation();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void buttonclick(View v)
    {
        final int posotion = (Integer) v.getTag();
        switch (v.getId())
        {
            case R.id.orderlist_button_qiang:
                //Toast.makeText(this, "抢单了" + posotion, Toast.LENGTH_SHORT).show();
                final Order order = orderList.get(posotion);
                Order orderUpdata = new Order();
                orderUpdata.setOrder_state(2);
                orderUpdata.setOrder_uid(BmobUser.getCurrentUser(_User.class).getUsername());
                orderUpdata.update(order.getObjectId(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){
                            Toast.makeText(OrderListActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                            orderList.remove(posotion);
                            adapter.notifyDataSetChanged();
                        }else{
                            Toast.makeText(OrderListActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case R.id.orderlist_item_layout:
                //Toast.makeText(this, "点击了查看详情" + posotion, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, OrderActivity.class);
                intent.putExtra("order_data", orderList.get(posotion));
                startActivity(intent);
                break;
        }
    }

    public void getOrderData()
    {
        final CustomDialog dialog = new CustomDialog(this, 100, 400, R.layout.dialog_loding,
                R.style.Theme_dialog, Gravity.CENTER,R.style.pop_anim_style);
        dialog.setCancelable(false);
        dialog.show();
        orderList.clear();
        //开启新线程来获取数据
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                //从服务器上获取订单列表
                BmobQuery<Order> query = new BmobQuery<Order>();
                //返回50条数据，如果不加上这条语句，默认返回10条数据
                query.setLimit(20);
                //查询状态为1，也就是待抢单的订单
                query.addWhereEqualTo("order_state", 1);
                _User user = BmobUser.getCurrentUser(_User.class);
                query.addWhereNotEqualTo("order_aid", user.getUsername());
                //执行查询方法
                query.findObjects(new FindListener<Order>()
                {
                    @Override
                    public void done(final List<Order> object, BmobException e)
                    {
                        if(e==null){
                            orderList.addAll(object);
                            runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    Toast.makeText(OrderListActivity.this, "查询成功：共"+ object.size() + "条数据。", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }else{
                            runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    dialog.dismiss();
                                    Toast.makeText(OrderListActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        }).start();
    }

}
